package com.api.oa.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.api.oa.exception.BadRequestException;
import com.api.oa.model.entity.YQMedCare;
import com.api.oa.model.entity.YQPatient;
import com.api.oa.services.YQPatientService;
import com.api.oa.utils.LocalRedis;
import com.api.shopapi.controller.BaseController;
import com.api.shopapi.entity.MyResult;
import lombok.SneakyThrows;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.RSAUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/yq/yQPatient")
public class YQPatientController extends BaseController {

    @Autowired
    private YQPatientService iYQPatientService;

    @Autowired
    LocalRedis redis;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public MyResult Add(@RequestBody YQPatient entity) {
        try {
            return iYQPatientService.add(entity) == 1 ? success(entity) : failed("操作失败");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }

    @RequestMapping(value = "/addBatch", method = RequestMethod.POST)
    public MyResult Add(@RequestBody List<YQPatient> entities, HttpServletRequest req) {
        try {

            String timestamp = req.getHeader("timestamp");
            final String sign = req.getHeader("sign");
            if (StrUtil.isEmpty(timestamp)) return failed("时间戳不能为空");
            if (StrUtil.isEmpty(sign)) return failed("认证未通过");
            String format = String.format("timestamp=%s&key=%s", timestamp, privateKey);
            String s = SecureUtil.md5(format);
            if (!s.equals(sign)) return failed("认证未通过");
            iYQPatientService.addBatch(entities);
            return success("操作成功");
        } catch (BadRequestException e) {
            return anomalous(e.getMessage());
        }

    }


    @RequestMapping(value = "/remove/{id}", method = RequestMethod.POST)
    public MyResult remove(@PathVariable String id) {
        try {
            iYQPatientService.remove(id);
            return success("删除成功!");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public MyResult update(@RequestBody YQPatient entity) {
        try {
            return iYQPatientService.update(entity) == 1 ? success("操作成功") : failed("操作失败");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public MyResult list(@RequestParam(defaultValue = "1") Integer pageIndex, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(required = false) Long pid) {
        try {
            return success(iYQPatientService.list(pid, pageIndex, pageSize));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public MyResult page(@RequestParam(defaultValue = "1") Integer pageIndex, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(defaultValue = "") String idCard, @RequestParam(required = false) String attendType, @RequestParam(required = false) String insCode) {
        try {
            return success(iYQPatientService.page(idCard, insCode, attendType, pageIndex, pageSize));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void page(@RequestParam(defaultValue = "1") Integer pageIndex, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(defaultValue = "") String idCard, @RequestParam(required = false) String attendType, @RequestParam(required = false) String insCode,HttpServletResponse res) {
        try {
           iYQPatientService.export(idCard, insCode, attendType, pageIndex, pageSize,res);
        } catch (Exception e) {
        }
    }


    @RequestMapping(value = "/one/{id}", method = RequestMethod.GET)
    public MyResult one(@PathVariable Long id) {
        try {
            return success(id == null ? null : iYQPatientService.one(id));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping(value = "/myQR/{id}", method = RequestMethod.GET)
    public void MyQR(@PathVariable Long id, HttpServletResponse res) throws IOException {
        String key = SecureUtil.md5(SecureUtil.md5(id + "") + DateUtil.currentSeconds());
        redis.set(key, id, 60 * 1000 * 3);
        QrCodeUtil.generate(key, 300, 300, "jpg", res.getOutputStream());
    }


    @RequestMapping(value = "/list/ins", method = RequestMethod.GET)
    public MyResult patientByIns(@RequestParam(defaultValue = "1") Integer pageIndex, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(required = false) Long userId, @RequestParam(required = false) String keyWord) {
        try {
            return success(iYQPatientService.patientByIns(userId, keyWord, pageIndex, pageSize));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping(value = "/all/patient", method = RequestMethod.GET)
    public MyResult allPatients(@RequestParam(required = false) String insCode) {
        try {
            return success(iYQPatientService.allPatient(insCode));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping("/upload")
    public MyResult uploadFile(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException, BadRequestException {
        List<YQPatient> entities = new ArrayList<>();
        ExcelUtil.readBySax(file.getInputStream(), 0, new RowHandler() {
            @SneakyThrows
            @Override
            public void handle(int i, long l, List<Object> list) {
                if (i == 0 && l > 0) {


                    try {
                        Object patientPhone = null;///list.get(0);
                        Object patientIdCard = list.get(6);
                        Object patientName = list.get(7);
                        // Object patientSex = list.get(3);
                        // Object patientFace = list.get(4);
                        //Object IdCardType = list.get(6);
                        //Object patientAddress = list.get(6);
//                    Object lat = list.get(7);
//                    Object lng = list.get(8);
                        Object patientIns = list.get(3);
                        //Object patientAddBed = list.get(10);
                        Object patientType = list.get(9);
                        Object patientLevel = list.get(8);
                        //Object attendType = list.get(13);
                        // Object disabled = list.get(14);

                        if (StrUtil.isEmptyIfStr(patientIdCard) || StrUtil.isEmptyIfStr(patientIns)) return;
                        if (!IdcardUtil.isValidCard(String.valueOf(patientIdCard))) return;
                        YQPatient yqInsEntity = new YQPatient();
                        yqInsEntity.setPatientIdCard(StrUtil.isBlankIfStr(patientIdCard) ? "" : String.valueOf(patientIdCard));
                        yqInsEntity.setPatientIns(StrUtil.isBlankIfStr(patientIns) ? "" : String.valueOf(patientIns).split("-")[0].trim());
                        yqInsEntity.setPatientName(StrUtil.isBlankIfStr(patientName) ? "" : String.valueOf(patientName));
                        //.setPatientIdCard(StrUtil.isBlankIfStr(patientIdCard) ? "" : String.valueOf(patientIdCard));
                        // yqInsEntity.setPatientSex(StrUtil.isBlankIfStr(patientSex) ? null : (Integer) patientSex);
                        // yqInsEntity.setIdCardType(StrUtil.isBlankIfStr(IdCardType) ? null : (Integer) IdCardType);
                        // yqInsEntity.setPatientFace(StrUtil.isBlankIfStr(patientFace) ? "" : String.valueOf(patientFace));
                        // yqInsEntity.setPatientAddress(StrUtil.isBlankIfStr(patientAddress) ? "" : String.valueOf(patientAddress));
//                    yqInsEntity.setLat(StrUtil.isBlankIfStr(lat) ? null : (Double) lat);
//                    yqInsEntity.setLng(StrUtil.isBlankIfStr(lng) ? null : (Double) lng);
                        /// yqInsEntity.setPatientAddBed(StrUtil.isBlankIfStr(patientAddBed) ? null : DateUtil.parse(String.valueOf(patientAddBed), "yyyy-MM-dd HH:mm:ss"));
                        yqInsEntity.setPatientType(0);
                        yqInsEntity.setPatientLevel(StrUtil.isBlankIfStr(patientLevel) ? null : parseLevel(String.valueOf(patientLevel).substring(0, 2)));
                        yqInsEntity.setAttendType(StrUtil.isBlankIfStr(patientType) ? null : String.valueOf(patientType).equals("居家照护") ? 0 : 1);
                        //yqInsEntity.setDisabled(StrUtil.isBlankIfStr(disabled) ? null : (Integer) disabled);
                        entities.add(yqInsEntity);
                    } catch (Exception e) {
                        throw new Exception(String.format("第%s行数据出现问题:%s", l, e.getMessage()));
                    }
                }

            }
        });
        iYQPatientService.addBatch(entities);
        return success(String.format("导入成功%d条数据", entities.size()));
    }

    private Integer parseLevel(String substring) {
        if (substring.equals("一级")) return 1;
        else if (substring.equals("二级")) return 2;
        else if (substring.equals("三级")) return 3;
        else if (substring.equals("四级")) return 4;
        else if (substring.equals("五级")) return 5;
        return 0;
    }
}
